<script setup lang="tsx">
import { ref, unref } from 'vue'
import { ElButton, ElImage, ElMessage, ElMessageBox } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { useTable } from '@/hooks/web/useTable'
import { Table, type TableColumn } from '@/components/Table'
import { getCartListWithProductInfo, deleteCart } from '@/api/cart/admin'
import type { CartWithProductInfo } from '@/api/cart/types'

// 搜索表单
const searchForm = ref({
  userId: undefined,
  skuId: undefined,
  createTime: []
})

// 表格相关
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const params = {
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      userId: searchForm.value.userId,
      skuId: searchForm.value.skuId,
      createTimeStart: searchForm.value.createTime[0],
      createTimeEnd: searchForm.value.createTime[1]
    }

    const res = await getCartListWithProductInfo(params)
    return {
      list: res.data.list,
      total: res.data.total
    }
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置处理
const handleReset = () => {
  searchForm.value = {
    userId: undefined,
    skuId: undefined,
    createTime: []
  }
  currentPage.value = 1
  getList()
}

// 删除购物车项目
const handleDelete = async (row: CartWithProductInfo) => {
  try {
    await ElMessageBox.confirm('确定要删除用户购物车里的商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteCart(row.cart.cartId)
    ElMessage.success('删除成功')
    getList() // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 表格列定义
const columns: TableColumn[] = [
  {
    field: 'cart.cartId',
    label: '购物车ID',
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'cart.userId',
    label: '用户ID',
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'productSku.skuId',
    label: 'skuId',
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'productSku.skuCode',
    label: 'skuCode',
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'productSku.title',
    label: '商品标题',
    minWidth: 150,
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'productSku.mainImg',
    label: '商品图片',
    minWidth: 100,
    align: 'center',
    headerAlign: 'center',
    slots: {
      default: (data: any) => {
        const url = data.row.productSku.mainImg
        return url ? (
          <div style="display: flex; justify-content: center; align-items: center;">
            <ElImage
              style="width: 80px; height: 80px"
              src={url}
              fit="cover"
              preview-src-list={[url]}
              preview-teleported
            />
          </div>
        ) : (
          <div style="display: flex; justify-content: center; align-items: center;">
            <span>无图片</span>
          </div>
        )
      }
    }
  },
  {
    field: 'productSku.price',
    label: '价格',
    align: 'center',
    headerAlign: 'center',
    formatter: (row: CartWithProductInfo) => `¥${row.productSku.price}`
  },
  {
    field: 'cart.qty',
    label: '数量',
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'cart.remark',
    label: '备注',
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'cart.createdAt',
    label: '创建时间',
    align: 'center',
    headerAlign: 'center'
  },
  {
    field: 'action',
    label: '操作',
    align: 'center',
    headerAlign: 'center',
    width: 100,
    slots: {
      default: (data: any) => {
        const row = data.row as CartWithProductInfo
        return (
          <ElButton type="danger" size="small" onClick={() => handleDelete(row)}>
            删除
          </ElButton>
        )
      }
    }
  }
]
</script>

<template>
  <ContentWrap title="购物车列表">
    <!-- 搜索区域 -->
    <el-form :model="searchForm" :inline="true" label-width="80px" class="mb-20px">
      <el-form-item label="用户ID">
        <el-input
          v-model.number="searchForm.userId"
          placeholder="请输入用户ID"
          clearable
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="商品ID">
        <el-input
          v-model.number="searchForm.skuId"
          placeholder="请输入商品ID"
          clearable
          style="width: 200px"
        />
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchForm.createTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <Table
      :columns="columns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total,
        pageSize: pageSize,
        currentPage: currentPage
      }"
      @register="tableRegister"
      @refresh="getList"
    />
  </ContentWrap>
</template>